<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\article\model;

use think\Cache;
use mip\Paginationm;
use think\Db;
use think\Log;
use think\Model;
use think\Controller;

class ArticleCategory extends Model
{
    public function getById($id){
        $cacheKey = 'c_articleCategory_getById_'.$id;
        $gg = Cache::get($cacheKey);
        if($gg){
            return $gg;
        }

        $cate=db('articlesCategory')->where('id',$id)->find();
        if($cate){
            $cate['adminurl'] =config('mipInfo')['domain'].'/admin/article/articleList/cid-'.$cate['id'].'/';
            $cate['url'] = $this->getUrl( $cate );
            $cate['fullurl'] = config('mipInfo')['domain'].$cate['url'];
        }

        Cache::set($cacheKey,$cate,60*60);
        Cache::tag('article_category',$cacheKey);
        return $cate;
    }

    public function getOne($where,$order="sort desc"){
        $mw = 'c_articleCategory_getOne_'.serialize($where) ;
        $cacheKey = md5($mw) ;

        $gg = Cache::get($cacheKey);
        if($gg){
            return $gg;
        }

        if(!$order || $order===''){
            $order='sort desc';
        }

        $cate=db('articlesCategory')->where($where)->order($order)->limit(1)->find();
        if($cate){
            $cate['adminurl'] =config('mipInfo')['domain'].'/admin/article/articleList/cid-'.$cate['id'].'/';
            $cate['url'] = $this->getUrl( $cate );
            $cate['fullurl'] = config('mipInfo')['domain'].$cate['url'];
        }

        Cache::set($cacheKey,$cate,60*60);
        Cache::tag('article_category',$cacheKey);
        return $cate;

    }

    public function getListByParent($pid = 0,$order='sort desc',$limit=100 ){
        return $this->getList(array('pid'=>$pid), $order, 1, $limit );
    }

    public function getList($where = null,$order='sort desc', $page = 1 ,$limit=100){

        if(!$order || $order===''){
            $order='sort desc';
        }

        if(!$page || $page===''){
            $page = 1;
        }
        if(!$limit || $limit===''){
            $limit = 100;
        }

        $dblst = db('articlesCategory')->where( $where )->page($page)->limit($limit)->order($order)->select() ;

        foreach ($dblst as $k=>$v){
            $v['url'] = $this ->getUrl($v);
            $dblst[$k] = $v;
        }

        return $dblst;
    }

    public function getUrl( $cate ){
        $url = '';
        if($cate['list_preurl']){
            $url = $cate['list_preurl'] .$cate['id'].'/';
        }else{
            $templeInfo = model('app\setting\model\Template')->getInfoByFileName( config('mipInfo')['template'] );
            if( $templeInfo ){
                $url = $templeInfo['list_preurls'][0] .$cate['id'].'/';
            }
        }
        return $url;
    }

    /**
     * 获取完整的树形结构
     */
    public function getFullTree(){
        // 先获得列表
        $cates = db('articlesCategory')->order('sort desc')->select();
        $catetree = list_to_tree($cates,'id','pid','children');

        return $catetree;
    }

    public function getTreeByParent($pid=0){
        $cates = db('articlesCategory')->where(array('pid'=>$pid))->order('sort desc')->select();
        $catetree = list_to_tree($cates,'id','pid','children');

        return $catetree;
    }

    public function getFullCascader(){
        $cacheKey = 'c_articleCategory_getFullCascader';
        $gg = Cache::get($cacheKey);
        if($gg){
            return $gg;
        }

        $all_cates = db('articlesCategory')->order('sort desc')->select();
        $arr = list_to_cascader($all_cates,'id','pid','id','title','children',0);

        Cache::set($cacheKey,$arr,60*60);
        Cache::tag('article_category',$cacheKey);
        return $arr;
    }

    public function doAddGetId($arr){
        $newId = db('articlesCategory')->insertGetId($arr);
        if($newId){

            // 获取parent fullid
            $pid = $arr['pid'];
            $pfullid = '';
            if($pid){
                $arrPFullid = db('articlesCategory')->where(array('id'=>$pid))->field('fullid')->find();
                $pfullid = $arrPFullid['fullid'];
            }

            $fullId = $pfullid.$newId.',';
            model('app\article\model\ArticleCategory')->doEdit($newId,array('fullid'=>$fullId ) );

            Cache::clear('article_category');
        }

        return $newId;
    }

    public function doEdit($id,$arr){

        // 获取原来的fullid
        $arrOldfullid = db('articlesCategory')->where(array('id'=>$id))->field('fullid')->find();
        $oldfullid = null;
        if($arrOldfullid){
            $oldfullid = $arrOldfullid['fullid'];
        }

        // 获取fullid
        $pid = $arr['pid'];
        $pfullid = '';
        if($pid){
            $arrPFullid = db('articlesCategory')->where(array('id'=>$pid))->field('fullid')->find();
            $pfullid = $arrPFullid['fullid'];
        }
        $fullId = $pfullid.$id.',';
        //$arr['fullid'] = $fullId;

        Db::startTrans();
        try {

            $res = db('articlesCategory')->where('id',$id)->update($arr);

            // 所有的子元素都要升级fullid
            if ($oldfullid && $oldfullid!=$fullId ) {
                db('articlesCategory')->where(array('fullid' => array('like', $oldfullid.'%' )) )
                    ->setField('fullid',Db::raw( "replace(fullid,'".$oldfullid."','".$fullId."') ")  ) ;

                // 更新所有相关文章的字段
                db('articles')->where(array('fullcid' => array('like', $oldfullid.'%' )) )
                    ->setField('fullcid',Db::raw( "replace(fullcid,'".$oldfullid."','".$fullId."') ")  ) ;
            }

            Cache::clear('article_category');
            Cache::clear('article');

            Db::commit();
            return 1;
        }catch (\Exception $db_err){
            Log::error( $db_err->getTraceAsString());
            Db::rollback();
            return -1;
        }


    }

    public function doDelById($id){
        $res =  db('articlesCategory')->where('id',$id)->delete();
        if($res!==false){
            Cache::clear('article_category');
        }

        return $res;
    }

    public function moveSort($id,$direct){
        // 先获得分类pid
        $arrpid = db('articlesCategory')->where('id',$id)->field('pid')->find();
        if( !$arrpid ){
            return 3;
        }

        // 获得分类下所有的分类列表
        $cates = db('articlesCategory')->where(array('pid' =>$arrpid['pid'] ) )->field('id')->order('sort asc ')->select();
        if(!$cates){
            return 5;
        }

        $pos = array_search(array('id'=>$id),$cates);

        // 如果是向上移动
        if($direct=='down' && $pos>0){
            $prev = $cates[$pos-1];
            $curr = $cates[$pos];

            $cates[$pos] = $prev;
            $cates[$pos-1] = $curr;
        }else if($direct=='up'&& $pos<count($cates)-1 ){
            $next = $cates[$pos+1];
            $curr = $cates[$pos];

            $cates[$pos] = $next;
            $cates[$pos+1] = $curr;
        }else{
            return  0;
        }

        foreach($cates as $k1=>$v1){
            db('articlesCategory')->where('id',$v1['id'])->update(['sort'=>$k1+1]);
        }
        Cache::clear('article_category');
        return 1;

    }




}